package sm.upgrade.util;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UpgradeContext {
	private UpgradeContext() {
	}

	private static final UpgradeContext context = new UpgradeContext();

	public static UpgradeContext getInstance() {
		return context;
	}

	private ClassPathXmlApplicationContext baseContext;

	private ClassPathXmlApplicationContext customerContext;

	private ClassPathXmlApplicationContext upgradeContext;

	public synchronized ClassPathXmlApplicationContext getOrCreateBaseContext() {
		if (baseContext == null) {
			baseContext = new ClassPathXmlApplicationContext("base.xml");
			baseContext.start();
		}
		return baseContext;
	}

	public synchronized ClassPathXmlApplicationContext getOrCreateCustomerContext() {
		if (customerContext == null) {
			customerContext = new ClassPathXmlApplicationContext("customer.xml");
			customerContext.start();
		}
		return customerContext;
	}

	public synchronized ClassPathXmlApplicationContext getOrCreateUpgradeContext() {
		if (upgradeContext == null) {
			upgradeContext = new ClassPathXmlApplicationContext("upgrade.xml");
			upgradeContext.start();
		}
		return upgradeContext;
	}

	public synchronized void dropBase() {
		if (baseContext != null) {
			baseContext.stop();
			baseContext.destroy();
			baseContext = null;
		}
	}

	public synchronized void dropCustomer() {
		if (customerContext != null) {
			customerContext.stop();
			customerContext.destroy();
			customerContext = null;
		}
	}

	public synchronized void dropUpgrade() {
		if (upgradeContext != null) {
			upgradeContext.stop();
			upgradeContext.destroy();
			upgradeContext = null;
		}
	}

	public synchronized void removeAll() {
		dropBase();
		dropCustomer();
		dropUpgrade();
	}
}
